import { getImgPath } from './assets'

export const uuid = () => {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++)
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)

  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  // @ts-expect-error
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'
  return s.join('')
}
export function formatTime(time: Date | number) {
  const date = new Date(time)
  return `${date.getFullYear()}-${convertLessTen(date.getMonth() + 1)}-${convertLessTen(
    date.getDate(),
  )} ${convertLessTen(date.getHours())}:${convertLessTen(date.getMinutes())} `
}
export function formatHours(time: Date | number) {
  const date = new Date(time)
  return `${convertLessTen(date.getHours())}:${convertLessTen(date.getMinutes())}:${convertLessTen(
    date.getSeconds(),
  )} `
}

export function formatDate(time: Date | number, separator = '-') {
  const date = new Date(time)
  return `${date.getFullYear()}${separator}${convertLessTen(
    date.getMonth() + 1,
  )}${separator}${convertLessTen(date.getDate())}`
}

export function formatWeeks(weeks: number[]) {
  let week = ''
  weeks.forEach((res) => {
    week += `周${convertWeek(res)}、`
  })
  return week.slice(0, week.length - 1)
}

export function convertLessTen(num: number) {
  if (num <= 9)
    return `0${num}`
  else
    return num
}

export function convertWeek(week: number) {
  switch (week) {
    case 1:
      return '一'
    case 2:
      return '二'
    case 3:
      return '三'
    case 4:
      return '四'
    case 5:
      return '五'
    case 6:
      return '六'
    default:
      return '日'
  }
}
export function orderConvertTime(second: number) {
  const minute = Math.floor((second / 60) % 60)
  const sec = Math.floor(second % 60)
  return `${minute < 10 ? `0${minute}` : minute}:${sec < 10 ? `0${sec}` : sec}`
}
/**
 * @description 验证手机号
 * @param {String} phoneStr
 * @returns {Boolean}
 */
export function validPhoneNum(phoneStr: string): boolean {
  // var mobile = /^((13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])+\d{8})$/
  const mobile = /^(1\d{10})$/
  return mobile.test(phoneStr)
}

/**
 * 加载字体
 */
export const loadFontFace = (facename: string) => {
  uni.loadFontFace({
    family: facename,
    source: `url("${getImgPath(`${facename}.ttf`)}")`,
    fail: (err) => {
      console.log('font load fail', err)
    },
  })
}

export const getDate = (date: string) => {
  return new Date(date.replaceAll('-', '/'))
}

let throttleTimer = 0
export const throttle = (cbk: Function, delay = 500) => {
  if (throttleTimer)
    return

  throttleTimer = setTimeout(() => {
    cbk()
    throttleTimer = 0
  }, delay)
}

// px转rpx
export const pxToRpx = (px: number) => {
  // 计算比例
  const scale = uni.upx2px(100) / 100
  return px / scale
}

export function getLastMonthDate(): string {
  const today = new Date()
  const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1)
  const yyyy = lastMonth.getFullYear()
  const mm = String(lastMonth.getMonth() + 1).padStart(2, '0')
  const dd = String(lastMonth.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}

/**
 * 格式化手机号 1111111111 --> 111****1111
 */
export const formatMobile = (mobile: string | number) => {
  const a = `${mobile}`
  return `${a.slice(0, 3)}****${a.slice(-4)}`
}

/**
 * 计算两个经纬度之间的距离
 */
export function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number) {
  const radius = 6371 * 1000 // 地球半径（单位：米）

  // 将经纬度转换为弧度
  const latRad1 = toRadians(lat1)
  const lonRad1 = toRadians(lon1)
  const latRad2 = toRadians(lat2)
  const lonRad2 = toRadians(lon2)

  // 使用Haversine公式计算距离
  const dlon = lonRad2 - lonRad1
  const dlat = latRad2 - latRad1
  const a
    = Math.sin(dlat / 2) ** 2
    + Math.cos(latRad1) * Math.cos(latRad2) * Math.sin(dlon / 2) ** 2
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  const distance = radius * c

  return distance
}

function toRadians(degrees: number) {
  return degrees * (Math.PI / 180)
}

export function getToday() {
  const date = new Date()
  // 获取日期：年月日
  const year = date.getFullYear()
  let month = (date.getMonth() + 1).toString()
  let day = date.getDate().toString()
  if (Number(month) >= 1 && Number(month) <= 9)
    month = `0${month}`

  if (Number(day) >= 0 && Number(day) <= 9)
    day = `0${day}`

  return `${year}-${month}-${day}`
}

let timer = 0
export const debounce = (cbk: Function, delay = 300) => {
  if (timer)
    clearTimeout(timer)

  timer = setTimeout(() => {
    cbk()
  }, delay)
}

export function findKeyByValue(obj: any, value: any) {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] === value)
      return key
  }
  return null
}
